package components.dialogs
{
	import MLP.mlp_loader;
	
	import SEApp.boxes.albums.se_previewItem;
	import SEApp.se_util;
	
	import UIFree.FX;
	import UIFree.FX.pageturner.pt_3DTurner;
	import UIFree.FX.pageturner.pt_alphaTurner;
	import UIFree.FX.pageturner.pt_basePageTurner;
	import UIFree.FX.pageturner.pt_circleTurner;
	import UIFree.FX.pageturner.pt_collectTurner;
	import UIFree.FX.pageturner.pt_creator;
	import UIFree.FX.pageturner.pt_heartTurner;
	import UIFree.ObjectEvent;
	import UIFree.controls.uif_arrowbutton;
	import UIFree.controls.uif_button;
	import UIFree.controls.uif_gbutton;
	import UIFree.controls.uif_hscrollArea;
	import UIFree.controls.uif_input;
	import UIFree.controls.uif_label;
	import UIFree.controls.uif_leavesBlock;
	import UIFree.controls.uif_panel;
	import UIFree.controls.uif_popupMenu;
	import UIFree.uif_bitmap;
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	import UIFree.uif_loader;
	
	import UIUtils.uif_MLPEncoder;
	import UIUtils.uif_util;
	import UIUtils.uif_utilBitmap;
	
	import classes.clt_events;
	import classes.clt_locale;
	import classes.clt_utils;
	
	import components.base.uif_source;
	import components.clt_component;
	import components.clt_popupMenu;
	import components.game.clt_collageItem;
	import components.game.clt_comments;
	import components.game.clt_gameItem;
	import components.game.clt_rateLine;
	import components.game.clt_stiker;
	import components.game.clt_stikers;
	import components.game.clt_votesView;
	import components.plugins.mlp.clt_mlpImage;
	
	import data.clt_data;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.PixelSnapping;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.GlowFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.text.TextFieldType;
	import flash.utils.ByteArray;

	public class clt_collageView extends clt_dialog {
		private var _loader			: uif_loader;
		private var _mlpImage		: clt_mlpImage;
		private var _swapImage		: uif_bitmap; 
		private var _imageLayer		: clt_component;
		private var _avatar			: uif_source;
		private var _rateLine		: clt_rateLine;
		private var _info			: uif_label;
		private var _fb				: uif_gbutton;
		private var _votes			: clt_votesView;
		private var _bButton		: uif_button;
		private var _fButton		: uif_button;
		private var _collageLink	: uif_label;
		private var _stiker			: clt_stiker;
		private	var _rb				: uif_gbutton;
		private var _mPos			: int;
		private var _collageList	: uif_hscrollArea;
		private var _myComment		: uif_ecomponent;
		private var _comments		: clt_comments;
		private var _waitNext		: Boolean;
		private var _winner			: Bitmap;
		
		private static const MAXNAMELENGTH	: int = 21;
		
		public function clt_collageView(parent:uif_component) {
			super(parent, (app.width - 620) / 2, 25, 622, 797, false, 1);
			var inner: Rectangle = getInner();
			
			_imageLayer = new clt_component(this, inner.x, inner.y, inner.width, inner.height);
			_loader 	= new uif_loader(_imageLayer, '', doComplete);
			_swapImage	= new uif_bitmap(); 
			_swapImage.x = _imageLayer.x;
			_swapImage.y = _imageLayer.y;
			_swapImage.visible = false;
			addChild(_swapImage);
			
			_stiker 	= new clt_stiker(this);

			_bButton = new uif_arrowbutton(this, inner.x + 5, inner.y + 560 / 2, 40, 87, 4, 'farrow');
			_fButton = new uif_arrowbutton(this, inner.x + inner.width - 45, inner.y + 560 / 2, 40, 80, 2, 'farrow');
			_bButton.setVisibility(false);
			_fButton.setVisibility(false);
			
			addEvent(MouseEvent.MOUSE_MOVE, doMove, stage);
			_bButton.addEvent(MouseEvent.CLICK, doButtonClick);
			_fButton.addEvent(MouseEvent.CLICK, doButtonClick);
			buttonsVisibility();
			
			var panel: uif_ecomponent = new uif_ecomponent(this, inner.x, inner.y + inner.width + 5, 510, 75);
		//	panel.x = inner.x + (inner.width - panel.width) / 2; 
			_votes = new clt_votesView(this, inner.x, panel.y - 295, 300, 320);
			_votes.align = uif_leavesBlock.BOTTOMALIGN;
			
			
			inner = panel.getInner();
			
			_info = new uif_label(panel, inner.x, inner.y, 200, 48, 'description');
			
			_fb = new uif_gbutton(panel, inner.x, inner.x + inner.height - 20, 200, 20, 'rtbt');
			_fb.addEvent(MouseEvent.CLICK, doShowVotes);
			
			var size: int = _fb.y + _fb.height - _info.y;
			_avatar = new uif_source(panel, inner.x + _info.width + 10, inner.y, size, size, 'preview');
			//_avatar.addEvent(MouseEvent.CLICK, doAvatarClick);
			
			_rateLine = new clt_rateLine(panel, inner.x + _avatar.x + _avatar.width + 5, inner.y, 310, size * 0.7);
			_rateLine.addEvent(clt_events.VOTE, doVote);
			_rateLine.addEvent(clt_events.VOTE2, doVoteDouble);
			
			_winner = uif_utilBitmap.loadAsBitmap(clt_servers.IMAGE_URL + 'winner.png', function(a_bmp: Bitmap): void {
				panel.addChild(_winner);
			});
			_winner.x = _rateLine.x + 10;
			_winner.y = _rateLine.y + 5;
			_winner.visible = false;
			
			_collageLink = new uif_label(panel, _rateLine.x, _rateLine.y + _rateLine.height + 4, _rateLine.width - 33, 18, 'minput');
			_collageLink.hint = clt.classes.locale.LINKTOCOLLAGE;
			_collageLink.textField.type = TextFieldType.DYNAMIC;
			
			_rb = new uif_gbutton(panel, _collageLink.x + _collageLink.width, 
											_collageLink.y, 30, 18, 'rtbt');
			_rb.addEvent(MouseEvent.CLICK, doPublicClick);
			_rb.text = 'p';
			_rb.hint = clt.sitedata.SAIDBUTTONHINT;
			
			inner = getInner();
			var nPanel: uif_panel = new uif_panel(this, inner.x, panel.y + panel.height + 5, inner.width, 90, 'block');
			_comments = se_util.createComponent(nPanel, clt_comments, 'items') as clt_comments;
			addEvent(clt_comments.NEWCOMMENT, doNewComment, _comments.listArea);
			
			workspace.addEventListener(clt_events.SHOWGAMEITEM, doShowGameItem);
			
			var menuList: Array = [
				{caption: clt.classes.locale.USERCOLLAGES, method: doAllCollages},
				{caption: clt.classes.locale.GOTOAUTOR, method: doGotoAutor},
				{caption: clt_locale.SAVETODISK, method: doSaveToDisk},
				{caption: clt_locale.SAVETOALBUM, method: doSaveToAlbum},
				{caption: clt_locale.SAVETOMYALBUM, method: doSaveToMyAlbum}
			];
			
			if (!clt.isBanUser) menuList.push({caption: clt.classes.locale.COMPLAINTOCOLLAGE, method: doBanRequest});
			var _menu: clt_popupMenu = new clt_popupMenu(this, _avatar, menuList, function (e: ObjectEvent): void {
				e.object.method();
			}, {
				orientation: uif_popupMenu.RIGHTPOSITION
			});
		}
		
		private function doSaveToDisk(): void {
			if (_mlpImage) clt.saveToFile(_mlpImage.bytes, clt.genFileNameCard(clt_data.MLPEXT));
			else {
				var bmd: BitmapData = se_util.bmpCopy(_loader).bitmapData;
				clt.saveToFile(clt.encodeFromJPG(bmd));
				bmd.dispose();
			}
		}
		
		private function doSaveToAlbum(): void {
			if (_mlpImage) noSaveMlp();
			else {
				var bmd: BitmapData = se_util.bmpCopy(_loader).bitmapData;
				clt.saveToAlbum(clt.encodeFromJPG(bmd));
				bmd.dispose();
			}
		}
		
		private function doSaveToMyAlbum(): void {
			if (_mlpImage) clt.toGameMLP(true, _mlpImage);
			else clt.toGameSend(true, se_util.bmpCopy(_loader).bitmapData);
		}
		
		private function noSaveMlp(): void {
			clt.alert(clt_locale.WARNING, clt_locale.NOSAVEMLP);
		}
		
		protected function updateStikerPos(): void {
			_stiker.x	= _imageLayer.x + _imageLayer.width - _stiker.width - 10;
			_stiker.y	= _imageLayer.y + _imageLayer.width - _stiker.height - 10;
		}
		
		protected function updateStiker(): void {
			_stiker.visible = _data.stiker > 0;
			if (_data.stiker) {
				var inner: Rectangle = getInner();
				_stiker.setID(_data.stiker, 80, updateStikerPos);
			}
		}
		
		public function doAllCollages(): void {
			clt.workspace.dispatchEvent(new ObjectEvent(clt_events.USERCOLLAGES, _data));
		}
		
		public function doGotoAutor(): void {
			navigateToURL(new URLRequest(_data.link));
		}
		
		public function doBanRequest(): void {
			clt.workspace.dispatchEvent(new ObjectEvent(clt_events.BANREQUEST, _data));
		}
		
		protected function doShowGameItem(e: ObjectEvent): void {
			if (e.object is uif_component) {
				var item: uif_component = e.object as uif_component;
				_collageList = item.parent.parent as uif_hscrollArea;
				showCollage(item._data);
			} else {
				showCollage(e.object);
			}
		}
		
		protected function doPublicClick(e: Event): void {
			clt.publicGameCollage(_data, clt.sitedata.SAIDCOLLAGETITLE, clt.sitedata.SAIDCOLLAGEDESCR);
		}
		
		protected function doButtonClick(e: MouseEvent): void {
			var newIndex: int = _collageList.selectIndex + _mPos;
			if ((newIndex >= 0) && (newIndex < _collageList.items.length)) {
				_collageList.selectIndex = newIndex;
				showCollage(_collageList.selectItem.object);
				buttonsVisibility(_mPos);
			}
		}
		
		protected function doMove(e: MouseEvent): void {
			if (visible) {
				var rect	: Rectangle = app.getOuter();
				var mPoint	: Point		= app.mousePos;
				rect.width /= 2;
				if (rect.containsPoint(mPoint)) mPos = -1;
				else mPos = 1;
			}
		}
		
		protected function set mPos(a_pos: int): void {
			if (_mPos != a_pos) {
				_mPos = a_pos;
				buttonsVisibility(_mPos);
			}
		}
		
		protected function buttonsVisibility(a_visible: int=0): void {
			if (_collageList && !_waitNext) {
				if ((a_visible == -1) && _collageList) {
					_bButton.alphaFX((_collageList.selectIndex>0)?0.5:0);
					_fButton.alphaFX(0);
				} else if ((a_visible == 1) && _collageList) {
					_bButton.alphaFX(0);
					_fButton.alphaFX((_collageList.selectIndex<_collageList.items.length-1)?0.5:0);
				} else if (a_visible == 0) {
					_bButton.alphaFX(0);
					_fButton.alphaFX(0);
				}
			}
		}
		
		protected function doShowVotes(e: Event=null): void {
			if (_votes.showState > 0) _votes.hide()
			else _votes.showVotes(_data.id);
		}
		
		protected function doAvatarClick(e: Event): void {
			if (_data.link) navigateToURL(new URLRequest(_data.link));
		}
		
		private function initSwapImage(source: DisplayObject): void {
			if (!_swapImage.bitmapData) 
				_swapImage.bitmapData = new BitmapData(600, 600, false)
			_swapImage.bitmapData.fillRect(_swapImage.bitmapData.rect, style.fill_color);
			_swapImage.bitmapData.draw(source);
			_swapImage.visible 		= true;
			_swapImage.alpha 		= 1;
		}
		
		private function setWaitNext(a_value: Boolean): void {
			_waitNext = a_value;
			if (_waitNext) {
				_bButton.setVisibility(false);
				_fButton.setVisibility(false);
			} else {
				buttonsVisibility(_mPos);
			}
		}
		
		public function showCollage(item: Object): void {
			if (item) {
				
				setWaitNext(true);
				_avatar.source.unload();
				_data = item;
				_stiker.visible = false;
				
				if (_data.pic) _avatar.loadSource(_data.pic);
				else _avatar.loadSource(clt.sitedata.EMPTYPICURL);
				title.text = clt.classes.locale.COLLAGE;
				
				if (_loader.loaded) {
					initSwapImage(_loader);
					_loader.unload();
					_loader.visible = false;
				} else if (_mlpImage) {
					initSwapImage(_mlpImage);
					_mlpImage.dispose();
					_mlpImage = null;
				}
				
				if (item.mlp) loadMLP();
				else {
					_loader.visible = true;
					_loader.load(new URLRequest(clt_servers.GAME_URL + _data.id + clt_data.JPGEXT));
				}
				
				_rateLine.vote = parseInt(_data.isMyVote);
				_rateLine.slideVisible(item.noVictory == 0);
				_collageLink.slideVisible(item.noVictory == 0);
				_rb.slideVisible(item.noVictory == 0);
				_winner.visible = item.noVictory != 0;
				updateInfo();
				show();
				if (_votes.showState > 0) _votes.hide()
			}
		}
		
		private function loadMLP(): void {
			function doCompleteMLPA(e: Event): void {
				a_loader.removeEventListener(Event.COMPLETE, doCompleteMLPA);
				uif_MLPEncoder.decode(a_loader.data as ByteArray, doCompleteMLP);
			}
			var a_loader: mlp_loader = new mlp_loader();
			a_loader.addEventListener(Event.COMPLETE, doCompleteMLPA);
			a_loader.load(new URLRequest(clt_servers.GAME_URL + _data.id + clt_data.JPGEXT));
		}
		
		protected function doCompleteMLP(bmps: Array): void {
			var rect: Rectangle = new Rectangle(_loader.x, _loader.y, 600, 600);//bmps[0].width, bmps[0].height);
			/*
			if (_mlpImage) {
				_mlpImage.FXCancel();
				_mlpImage.dispose();
				_mlpImage = null;
			}
			*/
			
			_mlpImage = new clt_mlpImage(_imageLayer, bmps, rect);
			swapImage();
		}
		
		protected function doComplete(e: Event): void {
			swapImage();
		}
		
		
		
		protected function swapImage(): void {
			if (_swapImage.bitmapData) {
				if (_mlpImage) {
					new FX(function(delta: Number): void {
						_swapImage.alpha = 1 - delta;
					}).start(function(): void {
						_swapImage.alpha = 0;
						updateStiker();
						setWaitNext(false);
					});
				} else {
					_swapImage.visible = false;
					var pt: pt_basePageTurner = pt_creator.random(this, _mlpImage != null);
					pt.position = _imageLayer.position;
					pt.prepare(_swapImage, _loader);
					(pt.slideFX()).start(function(): void {
						pt.dispose();
						updateStiker();
						setWaitNext(false);
					});
				}
			} else {
				updateStiker();
				setWaitNext(false);
			}
		}
		
		private function updateInfo(): void {
			
			var userName: String = se_util.userName(_data);
			
			_info.textField.y = 8;
			_info.textField.htmlText = 'Автор: <b>' + Utils.ll(userName, MAXNAMELENGTH) + '</b>\nДата: <b>' + Utils.mySQLTime(_data.time) + '</b>';
			
			if (userName.length > MAXNAMELENGTH) _info.hint = userName;
			else _info.hint = '';
			
			_fb.textField.htmlText 	 = 'Рейтинг: <font color="#FF0000"><b>' + _data.rate + '</b></font>';
			title.text = (_data.name)?_data.name:(clt.classes.locale.COLLAGE + ' №' + _data.id);
			_collageLink.text = clt.getCollageLink(_data);
			refreshComments();
		}
		
		public function refreshComments(): void {
			var startLoadID: uint = _data.id;
			clt.internalServer.listComment(startLoadID, function(a_data: Object): void {
				if (startLoadID == _data.id) doCommentsComplete(startLoadID, ((a_data.response[0] is Array)?a_data.response[0]:[]));
			});
			_comments.clear();
		}
		
		protected function doCommentsComplete(game_id: uint, list: Array): void {
			var nc: Object = {
				uid				: clt.externalServer.viewer_id,
				time			: clt.classes.locale.NEWCOMMENTTITLE,
				content_id		: _data.id,
				content_type	: clt_comments.CONTENTTYPE_COM,
				comment			: ''
			}
				
			if (!clt.isBanUser) {
				if (clt.user.myData.isMyGame.count == 0) {
					nc.comment		= clt.classes.locale.NOISGAME;
					nc.content_type = clt_comments.CONTENTTYPE_MSG;
				} else nc.content_type = clt_comments.CONTENTTYPE_NEW;
			} else {
				var inText: String = '';
				if (clt.user.myData.user.banType == clt_data.BANTEMPO) {
					inText = 'На ваши действия действует бан, до ' + clt.user.myData.user.banDate + ' ';
				}
				nc.comment		= Utils.sprintf(clt.classes.locale.BANCOMMENTS, inText);
				nc.content_type = clt_comments.CONTENTTYPE_MSG;
			}
			
			list.push(nc);
				
			if (list) {
				if (list.length) {
					if (list.length > 100)
						list.splice(0, list.length - 100);
					clt.externalServer.getProfiles(se_util.getUids(list), function(usersData: Array): void {
						if (game_id == _data.id) {
							list.forEach(function(item: Object, index: int, arr: Array): void {
								list[index] = uif_util.union(item, usersData.filter(function(itemUser: Object, index:int, arr: Array): Boolean {
									return itemUser.uid == item.uid;
								})[0]);
							});
							_comments.list = list;
							_comments.listArea.selectIndex = list.length - 1;
						}
					});
				} else _comments.list = list;
			}
		} 
		
		protected function doNewComment(e: ObjectEvent): void {
			clt.internalServer.addComment(clt.externalServer.viewer_id, e.object.content_id, e.object.comment, function(data: Object): void {
				if (_data.id == e.object.content_id) {
					refreshComments();
					clt.publicGameCollage(_data, clt.classes.locale.WARNING,  
						Utils.sprintf(clt.classes.locale.COMMENTSTREAM, Utils.sex(clt.user.sex, 'остави-л,ла'))
					);
				}
			});
		}
		
		protected function addVotes(a_votes: int): void {
			if (_data.dv_count) a_votes *= _data.dv_count * 2;
			 
			var newRate: int = parseInt(_data.rate) + a_votes;
			clt.internalServer.addVotes(_data.id, clt.externalServer.viewer_id, a_votes, newRate, function(a_data: Object): void {
				if (a_data.response[0].result == -1) {
					_data.isMyVote 	= a_votes;
					clt.alert(clt_locale.WARNING, clt_locale.ALREADYVOTE);
				} else {
					_data.isMyVote 	= a_votes;
					_data.rate 		= newRate;
					updateInfo();
					clt.workspace.dispatchEvent(new Event(clt_events.UPDATEGAME));
					clt.workspace.dispatchEvent(new ObjectEvent(clt_events.AFTERADDVOTE, _data));
				}
			});
		}
		
		protected function doVote(e: ObjectEvent): void {
			addVotes(e.object as int);
		} 

		protected function doVoteDouble(e: Event): void {
			clt.workspace.dispatchEvent(new ObjectEvent(clt_events.VOTE2, _data));
		} 
	}
}